// pages/map/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var amapFile = require('../../lib/amap-wx');
var myAmapFun;
import Notify from '../../components/@vant/weapp/dist/notify/notify'
// 地图标记点的气泡
var callout = []
var markers = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    speedValue:12,
    centerLng:'',
    centerLat:'',
    markers:[],
    polyline:[],
    id:'',
    show:false, // 显示病害信息
    latitude: '', // 现在所处位置
    longitude: '', // 现在所处位置
    from: '',
    to: '',
    distance: '',
    points: [], // 坐标点
    name:'', // 病害名称
    address:'', // 病害地址
    DisForm:{}, //病害信息
    updateTime:[],
    ToUrl:'', // 跳转病害详情信息页面
    toSelect: false, // 展示选择日期和时间  
    nowDate: '',
    nowCity: '鄞州区',
    showCity:false, // 展示所有地区
    CityForm:[],
    showDate:false, //展示选择月份
    currentDate: new Date().getTime(),
    // minDate: new Date().getTime(),
    Date:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    myAmapFun = new amapFile.AMapWX({key: '4e0a28c614e26768147e26d1945e842f'})
    let that = this
    that.getDate()
    that.getJingWeiDu();
    that.getDisForm()
    that.getAllCity();
  },

  //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置，天气情况等信
  loadGaode(latitude, longitude){
    let that = this
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
      success: function (data) {
        console.log(data);//全部数据
        that.setData({
          address: data[0].regeocodeData.formatted_address
        })
      },
      fail: function (info) {
        wx.showToast({
          title: info,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  async getDisForm(){
    this.setData({
      points: [],
      markers: []
    })
    console.log(this.data.nowCity,this.data.nowDate)
    const res = await request({
      url: '/newDiseases/getDiseasesByDateCity?city=' + this.data.nowCity + '&date=' + this.data.nowDate,
      // url : "/newDiseases/getDiseasesByDateCity?city=鄞州区&date=202104",
      method: "get",
    })
    console.log(res)
    if (res.errCode !== 200){
      var title = res.errMsg
      if(title == '参数异常') {
        Notify({
          message: '该地区本月暂无病害\n 若有其他疑问，请联系管理员。',
          type: 'danger',
          duration: 6000});
      }
      else{
         wx.showToast({
          title: title,
          icon: 'none',
          duration: 2000
        })
      }
      var that = this
      that.setData({
        // points: []
      })
    }
    else {
      wx.showLoading({
        title: '拼命加载中',
      })
      let listData = res.data
      var arr = []
      for (var i=0;i<listData.length; ++i){
        // 已修复的病害
        // if (listData[i].status == 1){
        //   continue;
        // }
        var url = '';
        if (listData[i].number <=5){
          url = '/imgs/2.png'
        }
        else if(listData[i].number <= 10){
          url='/imgs/1.png'
        }
        else {
          url='/imgs/3.png'
        }
       let lat = listData[i].latitude
       let lng = listData[i].longitude
       arr.push({
            latitude: lat,
            longitude: lng
        })
        markers = markers.concat({
          iconPath: url,
          id: listData[i].id,
          callout:{
            content: listData[i].name + '\t' + listData[i].type + '\n' + listData[i].city ,
            fontsize: '56rpx',
            padding: '24rpx',
            color: '#009199',
            display: 'BYCLICK',
            textAlign: 'center',
            borderRadius: '16rpx',
            borderColor: '#40739e',
            borderWidth: '6rpx'
          },
          latitude: lat,
          longitude: lng,
          width: '80rpx',
          height: '80rpx'
        })
        
        // that.setData({
        //   markers: markers,
        // }) 
      }
      // console.log(markers)
      this.setData({
        points: arr,
        markers: markers
      },()=>{
        wx.hideLoading({
          success: (res) => {},
        })
      })
      // console.log(that.data.points)
    }
  },
  // 获取当前月份
  getDate(){
    let time = new Date()
    this.toChangeTime(time)
  },
   // 日期转换
   toChangeTime(time){
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let months = ''
    if (month < 10) { months = '0' + month }
    this.setData({
      nowDate: year+''+months,
      Date: year +'年' + month +  '月'
    });
   },
// 点击查看隐患窗口
  CheckDge(e){
    console.log(e.detail)
    if (e.detail.markerId){
      this.getDgeInfos(e.detail.markerId)
      this.setData({
        show: true,
        id: e.detail.markerId,
        // 病害详情id传参跳转
        ToUrl: '/pages/diseases/details/index?Id='+ e.detail.markerId
      })
    }
  },
  async getDgeInfos(id){
    const res = await request({
      url : "/newDiseases/getOneDisease",
      data:{
        "id": id,
        "city": this.data.nowCity,
        "date":this.data.nowDate
      },
      method: "post"
    })
    console.log(res)
    if (res.errCode !== 200){
      var title = res.errMsg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      let time = res.data.updateTime.substring(0,10) + " " + res.data.updateTime.substring(12,16)
      console.log(time)
      this.setData({
        DisForm : res.data,
        updateTime: time
      })
      this.loadGaode(res.data.latitude,res.data.longitude)
    }
    this.loadGaode(this.data.latitude,this.data.longitude)
  },
  // 弹窗病害信息关闭
  onClose(){
    this.setData({
      show: false
    })
  },
  upLoad:function(){
    wx.navigateTo({
      url: '/pages/toUpload/index',
    })
  },
  // 选择日期和地区
  select:function(){
    this.setData({
      toSelect: true
    })
  },
  IsSelect(event) {
    console.log(event.detail);
  },
  onSelectClose() {
    this.getDisForm()
    this.setData({ toSelect: false });
  },

  // 选择地区
  async getAllCity(){
    const res = await request({
      url: '/newDiseases/getAllCities',
      method: "get",
    })
    if (res.errCode !== 200){
      var title = res.errMsg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      let arr = []
      let that = this
      let cityList = res.data
      cityList.forEach(function(item){
        arr.push(item.city)
      })
      // console.log(arr)
      that.setData({
        CityForm : arr
      })
    }
  },
  chooseCity(){
    this.setData({
      showCity: true
    })
  },
  onCityClose(){
    this.setData({
      showCity: false
    })
  },
  onCitySelect(event){
    this.setData({
      nowCity: event.detail.value
    })
    this.onCityClose()
  },

  // 选择日期
  chooseDate(){
    this.setData({
      showDate: true
    })
  },
  onDateClose()
  {
    this.setData({
      showDate: false
    })
  },
  onDateSelect(event) {
    let time = new Date(event.detail)
    this.toChangeTime(time)
    this.onDateClose()
  },
  onDateSelect1(event) {
    let time = new Date(event.detail)
    this.toChangeTime(time)
  },
  // 导航
  goToAddress(){
    let that = this
    wx.showLoading({
      title: '正在寻找导航',
    })
      wx.openLocation({
        // latitude: that.data.DisForm.latitude,
        // longitude: that.data.DisForm.longitude, 
        latitude: that.data.latitude,
        longitude: that.data.longitude, 
        // scale: 8, // 缩放比例
        name: that.data.name,
        address:that.data.address,
        success:function(r){
          wx.hideLoading({
            success: (res) => {},
          })
          console.log(r)
        }
      }) 
  },
   /**
   * 获取经纬度
   */
  getJingWeiDu() {
    // let that = this;
    // wx.getLocation({
    //   type: 'gcj02',
    //   success(res) {
    //     console.log(res);
    //     // wgs84->jcj02
    //     var a = that.data.points
    //     var str = res.latitude + ',' + res.longitude
    //     a.push({latitude: res.latitude ? res.latitude: null,longitude:  res.longitude ? res.longitude: null,})
    //     that.getCenterPoint();
    //     that.setData({
    //       longitude: res.longitude ? res.longitude: null,
    //       latitude: res.latitude ? res.latitude: null,
    //       centerLng: res.longitude ? res.longitude: null,
    //       centerLat: res.latitude ? res.latitude: null,
    //       points: a,
    //       from : str
    //     })
    //     that.loadGaode(res.latitude,res.longitude);//调用高德
    //   }
    // })
    let that = this
    myAmapFun.getRegeo({
      success:(ress)=>{
        console.log(ress)
        let res = ress[0]
        var a = that.data.points
        var str = res.latitude + ',' + res.longitude
        a.push({latitude: res.latitude ? res.latitude: null,longitude:  res.longitude ? res.longitude: null,})
        that.getCenterPoint();
        that.setData({
          longitude: res.longitude ? res.longitude: null,
          latitude: res.latitude ? res.latitude: null,
          centerLng: res.longitude ? res.longitude: null,
          centerLat: res.latitude ? res.latitude: null,
          points: a,
          from : str
        })
        that.loadGaode(res.latitude,res.longitude);//调用高德

      }
    })
  },

// 计算中心点

getCenterPoint(){
  let that  = this
  var mapCtx = wx.createMapContext("map");
  // console.log(that.data.polyline[0].points)
  var a =  that.data.points
  console.log(a)
  mapCtx.includePoints({
        padding: [100],
        points: a,
        success: function (e){
          that.setData({
             polyline: [{
              points: a,
              color:"#009199",
              width: 3,
              dottedLine: true
          }],
          })
        },
        fail: function (e){
          console.log(e)
        }

      })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})